Skip to main content

Bar Plot

df.plot(kind='bar', x=data_col, y=data_col)

Create a bar plot using a DataFrame.

Input:
kind : string
To create a bar plot, use kind='bar'
To create a horizontal bar plot, use kind='barh'
x : label, optional
Column containing categorical data for group labels. If not specified, the index of the DataFrame is used.
y : label, optional
Column containing numerical data for the groups in x. If not specified, all numerical columns are used.
Returns:
plot - Matplotlib plot created using parameters.
Return Type:
Matplotlib plot
Note:
  • When kind='bar', you can sort your DataFrame in descending order by your y column before plotting to create a vertical bar plot that goes from tall to short from left to right.
  • When kind='barh', you can sort your DataFrame in ascending order by your y column before plotting to create a horizontal bar plot that goes from tall to short from top to bottom.

# Creating a DataFrame to use for bar plots below
avg_species_weights = pets.get(['Species', 'Weight']).groupby('Species').mean().reset_index()
avg_species_weights
IndexSpeciesWeight
0cat8.8333333333
1dog48.3333333333
2hamster0.625
avg_species_weights.sort_values(by='Weight', ascending=False).plot(kind='bar', x='Species', y='Weight')

Bar plot example 1

If the group label is the index of the DataFrame, the x parameter can be omitted.

# Creating a DataFrame to use for bar plots below
species_count = pets.get(['Species','ID']).groupby('Species').count()
species_count = species_count.assign(Count = species_count.get('ID')).drop(columns = ['ID'])
species_count
IndexCount
cat3
dog3
hamster2
species_count.plot(kind='bar', y='Count', title='Distribution of Species');

Bar plot example 2

avg_species_weights.sort_values(by='Weight', ascending=True).plot(kind='barh', x='Species', y='Weight')

Bar plot example 3

pets.groupby('Species').count().plot(kind='bar', y='ID', title='Distribution of Species')

Bar plot example 3